package kamikaze.support;

import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class StringUtil {
	private static final Logger logger = Logger.getLogger(StringUtil.class.getName());

	public static final Pattern PATTERN_ALPHABET = Pattern.compile("^[a-zA-Z]+$");
	public static final Pattern PATTERN_ALPHANUMERIC = Pattern.compile("^[a-zA-Z0-9]+$");
	public static final Pattern PATTERN_EMAIL = Pattern
			.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

	public static String ensureNotBlank(String text, String name) {
		if (text == null || text.isEmpty()) {
			return name + " can not be empty";
		}

		return null;
	}

	public static String ensureMatch(String text, Pattern pattern, String errorMessage) {

		if (!pattern.matcher(text).find()) {
			return errorMessage;
		}

		return null;
	}

	public static boolean isAlphabetOnly(String string) {
		Pattern pattern = Pattern.compile("^[a-zA-Z]+$");
		Matcher matcher = pattern.matcher(string);

		return matcher.matches();
	}

	public static boolean isAlphaNumeric(String string) {
		Pattern pattern = Pattern.compile("^[a-zA-Z0-9]+$");
		Matcher matcher = pattern.matcher(string);

		return matcher.matches();
	}

	public static boolean isEmailAddress(String string) {
		Pattern pattern = Pattern
				.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
		Matcher matcher = pattern.matcher(string);

		return matcher.matches();
	}

	public static boolean isVisaCard(String cardNo) {

		if (cardNo.length() != 12 || cardNo.length() != 16) {
			return false;
		}

		Pattern pattern = Pattern.compile("^4[0-9]{12}(?:[0-9]{3})?$");
		Matcher matcher = pattern.matcher(cardNo);

		return matcher.matches();
	}

	public static boolean isMasterCard(String cardNo) {

		if (cardNo.length() != 16) {
			return false;
		}

		Pattern pattern = Pattern.compile("^5[1-5][0-9]{14}$");
		Matcher matcher = pattern.matcher(cardNo);

		return matcher.matches();
	}

	public static String sanitize(String string) {
		return string.replaceAll("(?i)<script.*?>.*?</script.*?>", "") // case 1
				.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "") // case 2
				.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", ""); // case 3
	}

	public static String encrypt(String plaintext) {

		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[16], "AES"));

			return new BigInteger(cipher.doFinal(plaintext.getBytes("UTF-8"))).toString(64);

		} catch (Exception e) {
			logger.log(Level.WARNING, "", e);
			return plaintext;
		}
	}
}
